package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHUtil
import org.json.JSONObject

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse



/**
 * @Title:获取企微信息
 * @Description:提供给平安期货侧开发调用-获取对应手机号的客户经理企微信息
 * @Param:
 * @return:
 * @Author: TH
 * @Date: 2024/9/9
 */
public  class apiCheckQWMsg implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiCheckQWMsg.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        
        response.setContentType("application/json;charset=UTF-8");

        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 获取接口调用方式及参数
        String getMethod = request.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        try {
            if (KHUtil.isNull(inData)){
                log.error("【apiCheckQWMsg】调用参数为空！");
                result.put("code","-1");
                result.put("msg","【apiCheckQWMsg】调用参数为空！");
                return result.toString();
            }
            JSONObject dataJson  = new JSONObject(inData);
            String Mobile=KHUtil.GetJV(dataJson,"Mobile");//手机号

            String dealmsg=KHUtil.isNullMSG("Mobile",Mobile);

            if (!KHUtil.isNull(dealmsg)){
                log.error("【apiCheckQWMsg】调用参数为空:"+dealmsg);
                result.put("code","-1");
                result.put("msg","【apiCheckQWMsg】调用参数值为空："+dealmsg+"注:请注意参数大小写！");
                return result.toString();
            }

            //查询是否存在开户数据
            String khsql='''  select  t2.staffname,t2.Weixinid,t2.staff_id  from dws.paqh_userinfo t1 
                                       left join staff t2 on t2.staffname=t1.finance_manager
                                           where t1.mobile=? and t1.canceldate is null and t1.finance_manager is not null limit 1                                   
                                         '''
            List<Map<String, Object>> KhList = jt.queryForList(khsql,Mobile);


            if (KhList.size()>0){
                String Weixinid=KhList.get(0).get("Weixinid");//企微ID
                String staffname=KhList.get(0).get("staffname");//人员名字
                String staff_id=KhList.get(0).get("staff_id");//人员ID

                String qwListSQL2=''' select q.rec_guid from qw_relevance_list q left join staff s on s.staff_id =q.staff_id where q.mobile =? and s.Workstatus = 'ONLINE'   Limit 1 ''';

                List<Map<String, Object>> qw2List = jt.queryForList(qwListSQL2,Mobile);
                if (qw2List.size()>0){
                    String rec_guid=qw2List.get(0).get("rec_guid");
                    String UpdateSql='''update qw_relevance_list set Weixinid=?,staffname=?,staff_id=? where rec_guid=? ''';
                    jt.update(UpdateSql,Weixinid,staffname,staff_id,rec_guid);
                }else{
                    //插入企微信息表
                    String InsertSql='''Insert into qw_relevance_list (rec_guid,Weixinid,staffname,staff_id,mobile,Createddate)values(uuid(),?,?,?,?,now())''';
                    jt.update(InsertSql,Weixinid,staffname,staff_id,Mobile);
                }
                result.put("code","0");
                result.put("msg","【集中作业平台】处理成功,查询到有开户名单对应坐席！");
                result.put("Weixinid",Weixinid);
                result.put("staffname",staffname);
            }else{
                //1.通过手机号查询客户是否存在在集中作业平台
                String qwListSQL=''' Select q.mobile,q.rec_guid,q.staff_id,q.Weixinid,q.staffname from qw_relevance_list q left join staff s on s.staff_id =q.staff_id where q.mobile =? and s.Workstatus = 'ONLINE'   Limit 1 ''';

                List<Map<String, Object>> qwList = jt.queryForList(qwListSQL,Mobile);

                if (qwList.size()>0){

                    String mobile=qwList.get(0).get("mobile");
                    String Weixinid=qwList.get(0).get("Weixinid");
                    String staffname=qwList.get(0).get("staffname");
                    result.put("code","0");
                    result.put("msg","【集中作业平台】处理成功！");
                    result.put("mobile",mobile);
                    result.put("Weixinid",Weixinid);
                    result.put("staffname",staffname);

                }else{

                    String customerListSql='''select  s.Weixinid,s.staff_id,s.staffname from elitetask e left join staff s on s.staff_id=e.Handleby_Id left join customer c on c.customer_guid=e.customer_guid where c.mobile =? and e.MAP_ID='4CA2PP' and  s.Workstatus = 'ONLINE'  limit 1 ''';
                    List<Map<String, Object>> CKList = jt.queryForList(customerListSql,Mobile);
                    if (CKList.size()>0){
                        //查询是否存在电销促开数据
                        if (CKList.size()>0){
                            String Weixinid=CKList.get(0).get("Weixinid");//企微ID
                            String staffname=CKList.get(0).get("staffname");//人员名字
                            String staff_id=CKList.get(0).get("staff_id");//人员ID
                            result.put("code","0");
                            result.put("msg","【集中作业平台】处理成功,查询到有电销促开名单对应坐席");
                            result.put("Weixinid",Weixinid);
                            result.put("staffname",staffname);

                            //插入企微信息表
                            String InsertSql='''Insert into qw_relevance_list (rec_guid,Weixinid,staffname,staff_id,mobile,Createddate)values(uuid(),?,?,?,?,now())''';
                            jt.update(InsertSql,Weixinid,staffname,staff_id,Mobile);


                        }else{
                            Map Backmap=GetRandomStaff_QWID(eliteBean,Mobile);
                            result.put("code",Backmap.get("code"));
                            result.put("msg",Backmap.get("msg"));
                            result.put("Weixinid",Backmap.get("Weixinid"));
                            result.put("staffname",Backmap.get("staffname"));
                        }
                    }else{
                        Map Backmap=GetRandomStaff_QWID(eliteBean,Mobile);
                        result.put("code",Backmap.get("code"));
                        result.put("msg",Backmap.get("msg"));
                        result.put("Weixinid",Backmap.get("Weixinid"));
                        result.put("staffname",Backmap.get("staffname"));

                    }




                }

            }










        } catch (Exception e) {
            log.error("【apiCheckQWMsg】获取对应手机号的客户经理企微信息异常", e);
            result.put("code","-1");
            result.put("msg","【集中作业平台】获取企微信息异常："+e);
            return result.toString();
        }


        log.debug("【apiCheckQWMsg】返回参数："+result.toString());

        return result.toString();
    }

    /**
     * @Title:查询不到客户，以及不存在预约、开户名单数据，随机返回电销分配的客户经历企微ID
     * @Description:，
     * @Param:
     * @return:
     * @Author: TH
     * @Date: 2024/9/9
     */
    public static Map<String, String> GetRandomStaff_QWID(EliteBean eliteBean, String mobile) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        Map<String, String> map= new HashMap<String, String>();

        //初始化随机人员数据
        String insertStaffSQL = ''' Insert Into Hst_Rule_Issue_Control
                 (Rule_Id, Staff_Id, Assign_Date, Assign_Num, Last_Check_Time)
                 Select '999', Staff_Id, Date_Format(Now(), '%Y-%m-%d'), 0, Now()
                   From Staff
                  Where   Workstatus = 'ONLINE' and auto_allocation = 0
                    And  (Weixinid!='' and  Weixinid is not null)
                    And DEFAULTROLEGROUP='LMGVGI'
                    And Staff_Id Not In (Select Staff_Id
                                           From Hst_Rule_Issue_Control
                                          Where Rule_Id = '999'
                                            And Assign_Date = Date_Format(Now(), '%Y-%m-%d'))''';

        jt.update(insertStaffSQL);
        // 取当前名单下发最少的坐席
        String getAssginStaffSQL ='''
                                  select t2.Weixinid,t2.staff_id,t2.staffname,t1.Rec_id from Hst_Rule_Issue_Control  t1  
                                      left join staff t2 on t1.staff_id=t2.staff_id
                                       where t1.Rule_Id='999' and t2.auto_allocation = 0  
                                        and t2.Workstatus = 'ONLINE'
                                        And t1.Assign_Date = Date_Format(Now(), '%Y-%m-%d')
                                        order by t1.Assign_Num asc Limit 1  
                                         ''';
        List<Map<String, Object>> AssList = jt.queryForList(getAssginStaffSQL);

        if (AssList.size()>0){
            String Weixinid=AssList.get(0).get("Weixinid");//企微ID
            String Rec_id=AssList.get(0).get("Rec_id");//处理编号
            String staffname=AssList.get(0).get("staffname");//人员名字
            String staff_id=AssList.get(0).get("staff_id");//人员ID

            map.put("code","0");
            map.put("msg","【集中作业平台】处理成功！");
            map.put("Weixinid",Weixinid);
            map.put("staffname",staffname);

            //更新下发表
            String UpdateSql='''update Hst_Rule_Issue_Control  set Assign_Num = Assign_Num + 1, Last_Check_Time = Now()  where Rec_Id = ? ''';
            jt.update(UpdateSql,Rec_id);
            //插入企微对应表信息
            String InsertSql='''Insert into qw_relevance_list (rec_guid,Weixinid,staffname,staff_id,mobile,Createddate)values(uuid(),?,?,?,?,now())''';
            jt.update(InsertSql,Weixinid,staffname,staff_id,mobile);

        }else{
            map.put("code","-3");
            map.put("msg","【集中作业平台】未找到随机对应的坐席企微信息!");
        }





        return map;
    }
}
